import { resolve } from 'path';
import { UserConfigExport, ConfigEnv, loadEnv } from 'vite';
import {warpperEnv, configPluginList} from './build'

/** 当前执行node命令时文件夹的地址（工作目录） */
const root: string = process.cwd();

/** 路径查找 */
const pathResolve = (dir: string): string => resolve(process.cwd(), '.', dir);

/** 设置别名 */
const alias: Record<string, string> = {
  '@': pathResolve('src')
};

/**
 * @description:
 * @param {ConfigEnv} configEnv
 * @return {*}
 */
export default function (configEnv: ConfigEnv): UserConfigExport {
  const viteEnv = warpperEnv(loadEnv(configEnv.mode, root));
  const outDir = resolve(process.cwd(), `../dist/${viteEnv.VITE_BUILD_OUTDIR}`)

  viteEnv.outDir = outDir;

  const proxyMap: any = {};
  if (viteEnv.VITE_PROXY_INTERCEPT) {
    let list = viteEnv.VITE_PROXY_INTERCEPT.split(';');
    list.forEach((item) => {
      let [prefix, host, replace] = item.split(',');
      let proxyPrefix = `${viteEnv.VITE_PROXY_PREFIX}${viteEnv.VITE_APP_API_BASEURL}/${prefix}`
      proxyMap[proxyPrefix] = {
        target: host,
        changeOrigin: true,
        rewrite: (path: string) => path.replace(proxyPrefix, replace),
        cookieDomainRewrite: {
          '*': ''
        }
      }
    })
  }

  return {
    base: viteEnv.VITE_PUBLIC_PATH,
    root,
    resolve: {
      alias,
    },
    css: {
    },
    define: {
      'VITE_APP_VERSION': viteEnv.timeVersion
    },
    plugins: configPluginList(configEnv, viteEnv),
    build: {
      outDir
    },
    server: {
      // 端口号
      port: viteEnv.VITE_PORT,
      host: true,
      cors: true,
      proxy: {
        ...proxyMap,
        [viteEnv.VITE_PROXY_PREFIX]: {
          target: viteEnv.VITE_PROXY,
          changeOrigin: true,
          rewrite: (path) => path.replace(viteEnv.VITE_PROXY_PREFIX, ''),
          cookieDomainRewrite: {
            '*': ''
          }
        },
      },
    },
  };
}
